<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="状态标志" prop="available">
        <el-input
          v-model="queryParams.available"
          placeholder="请输入状态标志"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-permisaction="['community:posting:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >发帖</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['community:posting:edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-permisaction="['community:posting:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删帖</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="communitypostingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="用户"
        align="center"
        prop="authorInfo"
        :show-overflow-tooltip="true"
        width="100"
      >
        <template slot-scope="scope">
          <div>
            <img
              :src="scope.row.authorInfo.avatar"
              style="width:auto ;height:40px;margin-right:5px"
            />
            {{scope.row.authorInfo.nickname}}
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="内容"
        align="center"
        prop="content"
        :show-overflow-tooltip="true"
        width="200"
      >
        <template slot-scope="scope">
          <div v-html="scope.row.content.content"></div>
        </template>
      </el-table-column>

      <el-table-column
        label="图片"
        align="center"
        prop="image"
        width="180"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <div style="display: flex;flex-wrap: nowrap;">
            <div v-for="(item,index) in scope.row.image" :key="index">
              <img :src="item.url" style="width:auto ;height:40px;margin-right:5px" />
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="点击数" align="center" prop="hit" :show-overflow-tooltip="true" />
      <el-table-column label="回复数" align="center" prop="replyNum" :show-overflow-tooltip="true" />
      <el-table-column label="点赞数" align="center" prop="upVote" :show-overflow-tooltip="true" />
      <el-table-column label="差评数" align="center" prop="downVote" :show-overflow-tooltip="true" />
      <el-table-column label="收藏数" align="center" prop="favourite" :show-overflow-tooltip="true" />
      <el-table-column label="是否上架" align="center" prop="available" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.available"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'available','上架')"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" prop="topFlag" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.topFlag"
            active-value="T"
            inactive-value="F"
            @change="handleSwitchChange(scope.row,'topFlag','置顶')"
          />
        </template>
      </el-table-column>

      <el-table-column label="权重" align="center" prop="weigh" :show-overflow-tooltip="true" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        :show-overflow-tooltip="true"
        width="165"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        :show-overflow-tooltip="true"
        width="165"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-permisaction="['community:posting:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-permisaction="['community:posting:comment']"
            size="mini"
            type="text"
            icon="el-icon-s-comment"
            @click="handleComment(scope.row)"
          >评论</el-button>
          <el-button
            v-permisaction="['community:posting:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageIndex"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" style="align-items:flex-start">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="authorInfo">
          <div v-if="form.postingId">
            <el-avatar :src="form.authorInfo.avatar"></el-avatar>
            {{form.authorInfo.nickname}}
          </div>
          <div v-else>
            <el-select v-model="form.authorId" filterable placeholder="请选择官方用户">
              <el-option
                v-for="item in officeuserOptions"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="form.content.content"></el-input>
        </el-form-item>

        <el-form-item label="图片" prop="Image">
          <el-upload
            ref="upload"
            name="upload"
            :action="uploadImageAction"
            :headers="myHeader"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :multiple="true"
            :limit="9"
            :file-list="form.image"
            :on-success="handlepostingImageSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="是否上架" prop="available">
          <el-switch v-model="form.available" active-value="T" inactive-value="F"></el-switch>
        </el-form-item>
        <el-form-item label="是否置顶" prop="topFlag">
          <el-switch v-model="form.topFlag" active-value="T" inactive-value="F"></el-switch>
        </el-form-item>

        <el-form-item label="权重" prop="weigh">
          <el-input-number v-model="form.weigh" placeholder="权重"></el-input-number>
        </el-form-item>

        <el-form-item label="点击数" prop="hit">
          <el-input-number v-model="form.hit" placeholder="点击数"></el-input-number>
        </el-form-item>
        <el-form-item label="回复数" prop="replyNum">
          <el-input-number v-model="form.replyNum" placeholder="回复数"></el-input-number>
        </el-form-item>
        <el-form-item label="点赞数" prop="upVote">
          <el-input-number v-model="form.upVote" placeholder="点赞数"></el-input-number>
        </el-form-item>
        <el-form-item label="差评数" prop="downVote">
          <el-input-number v-model="form.downVote" placeholder="差评数"></el-input-number>
        </el-form-item>
        <el-form-item label="收藏数" prop="favourite">
          <el-input-number v-model="form.favourite" placeholder="收藏数"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 评论 start-->
    <el-dialog :title="titleComment" :visible.sync="openComment" width="80%" style="align-items:flex-start">
      <comment :originId="CommentPostingId" origin="community" />
    </el-dialog>
    <!-- 评论 end-->
    <!-- 图片预览 start-->
    <el-dialog :visible.sync="dialogVisible" style="align-items:flex-start">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <!-- 图片预览 end-->
  </div>
</template>

<script>
import {
  listCommunityPosting,
  getCommunityPosting,
  delCommunityPosting,
  addCommunityPosting,
  updateCommunityPosting,
} from "@/api/community/posting";

import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { getToken } from "@/utils/auth";

import comment from "@/components/MyComment";

export default {
  name: "CommunityPosting",
  components: {
    //使用编辑器
    quillEditor,
    comment,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        available: undefined,
      },
      // 表单参数
      form: {
        postingId: undefined,
        available: "T",
        topFlag: "F",
        hit: 0,
        replyNum: 0,
        upVote: 0,
        downVote: 0,
        favourite: 0,
        weigh: 0,
        content: {
          content: "",
        },
        image: [],
        authorInfo: {
          avatar: "",
          nickname: "",
        },
      },
      // 表单校验
      rules: {
        available: [
          { required: true, message: "状态标志不能为空", trigger: "blur" },
        ],
      },
      //帖子列表
      communitypostingList: [],
      //图片预览
      uploadImageAction:
        process.env.VUE_APP_BASE_API + "/api/v1/common/uploadImage",
      postingImageList: [],
      dialogImageUrl: null,
      dialogVisible: false,
      myHeader: {
        Authorization: "Bearer " + getToken(),
      },
      //官方用户列表
      officeuserOptions: [],
      //是否显示评论弹出层
      openComment: false,
      //评论弹出层标题
      titleComment: "",
      //查看评论的帖子ID
      CommentPostingId: undefined,
    };
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  created() {
    this.getList();
    this.officeuserOptions = this.$store.getters.parameter.general_user_office;
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listCommunityPosting(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((response) => {
        this.communitypostingList = response.data.list;
        this.total = response.data.count;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postingId: undefined,
        available: "T",
        topFlag: "F",
        hit: 0,
        replyNum: 0,
        upVote: 0,
        downVote: 0,
        favourite: 0,
        weigh: 0,
        content: {
          content: "",
        },
        image: [],
        authorInfo: {
          avatar: "",
          nickname: "",
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "发帖";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postingId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postingId = row.postingId || this.ids;
      getCommunityPosting(postingId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改帖子";
        this.postingImageList = this.form.image.map(function (e) {
          return {
            name: e.name,
            url: e.url,
          };
        });
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.postingId !== undefined) {
            updateCommunityPosting(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addCommunityPosting(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.postingId || this.ids;
      this.$confirm('是否确认删除编号为"' + Ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delCommunityPosting(Ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    //评论按钮操作
    handleComment(row) {
      // console.log(row);
      this.CommentPostingId = row.postingId;
      this.openComment = true;
      this.titleComment = "评论";
    },

    //图片上传 start
    postingImageBeforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message({
          message: "上传图片只能是 JPG或PNG 格式!",
          type: "warning",
        });
        return false;
      }
      if (!isLt2M) {
        this.$message({
          message: "单个文件 " + file.name + " 不能大于2M",
          type: "warning",
        });
        return false;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.form.image = fileList;
      console.log(this.form.image);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //上传组图成功
    handlepostingImageSuccess(res, file) {
      console.log(res.data);
      if (res.code == "200") {
        this.form.image.push(res.data);
        //解决关键代码：使用延时器清空上传文件列表和自定义参数，
        setTimeout(
          () => this.$store.commit("basic/addGallery", response[0]),
          1000
        );
      }

      //   this.postingImageList = this.form.image;
      console.log(this.form.image);
    },

    //图片上传 end

    // 帖子状态修改
    handleSwitchChange(row, filed, tipStr) {
      const text = row[filed] === "T" ? "启用" : "停用";
      console.log(row[filed]);
      this.$confirm('确认要"' + text + row.id + tipStr + '"功能吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          let updateData = row;
          updateData["postingId"] = row.postingId;
          updateData[filed] = row[filed];
          console.log(updateData);

          updateCommunityPosting(updateData).then((response) => {
            if (response.code === 200) {
              return true;
            } else {
              this.msgError("修改失败");
              return false;
            }
          });

          // return changeUserStatus(row.userId, row.status)
        })
        .then(() => {
          this.msgSuccess(text + row.title + tipStr + "成功");
          //   this.getList();
        })
        .catch(function () {
          // row.status = row.status === "0" ? "1" : "0";
        });
    },
  },
};
</script>